# NarutoCN Image Getter
# Get cartoon pictures from www.narutocn.net automatically
# chuanshenglu@gmail.com
# usage:
#         perl getimg.pl [base_url] [start_series] [end_series] [output zip:1/0] [verbose:1/0]
#  e.g.  perl getimg.pl http://comic-zj.narutocn.net/comic/bleach 251 300
#!/usr/bin/perl -w

use LWP::Simple;
use LWP::UserAgent;
use File::Spec;

my ( $base_url, $start_series, $end_series, $if_zip, $if_verbose ) = @ARGV;

defined($base_url) || ($base_url="http://comic-zj.narutocn.net/comic/naruto");
my $postfix="png";
my $url="$base_url/$series/$n.png";
my $root=File::Spec->rel2abs("./");
my $progress_len=0;

( defined( $start_series) && defined( $end_series) ) || die "Must specify the start, end series\n";
defined($MAX_SERIES) || ($MAX_SERIES=400);
defined( $if_zip) || ($if_zip=0);
defined( $if_verbose) || ($if_verbose=0);

chdir $root;
my $errlog="error_log.txt";                   #log error messages in error log;
!(-d "$errlog") || `rm -f $errlog`;
open ERRLOG,"+>$errlog";

print "[";
#foreach( my $series=$start_series; $series<=$end_series;++$series)
foreach my $series ($series_start..$series_end)
{
    # the series befor 430 (not included) is JPG format;
 #   $postfix=get_img_postfix("$base_url/$_");

    #make directory for each series;
    my $dir="$root/$_";
    ($if_verbose==0) || (print "mkdir $dir\n");
    mkdir $dir;
    ($if_verbose==0) || (print "change dir to $dir\n");
    chdir $dir;
    my $dir_error=0;
    my $sname=&make_file_name( $series); 
    if($series<=32){
        $postfix=get_mg_postfix("$base_url/vol_$sname");
    }else{
        $postfix=get_mg_postfix("$base_url/$sname");
    }

    #Retrieve pictures from server;
    foreach( 1..1024)
    {
        my $fname=&make_file_name( $_ ).".$postfix";
        if($series<=32){
            $url="$base_url/vol_$sname/$fname";
        }else{
            $url="$base_url/$sname/$fname";
        }
        print "$url\n";
        ($if_verbose==0) || (print "Get: $url\n");
        my $ua = new LWP::UserAgent;
        my $response = $ua->get( $url, 
                                 ':content_file' => "$fname" );

        #if got abnormal response jump to the next loop
        if( !($response->filename eq $fname) || $response->is_error)
        {
            ($n!=1) || ($dir_error=1);      #if only one was downloaded, error occurs!!!
            `rm -rf $fname` unless !(-e $fname);
            last;
        }else{
            print "#";
            flush STDOUT;
        }
    }
    chdir $root;
    if($dir_error==1){        #If error, delete the directory;
        `rm -rf $dir`;
        print ERRLOG "Fail to download $url\nDelete incompleted directory $root/$s";
        next;
    }
    do{
        ($if_verbose==0) || (print "Compress dir $series into $series.zip\n");
        `perl archdir.pl $root`;
    }unless ($if_zip==0);
    
    #print_progress($series);
}
print "]\n";
 close ERRLOG;

#generate full file name from simple numbers
sub make_file_name{
    my ($num)=@_;
    $num<10 && (return "00$num");
    $num<100 && (return "0$num");
    return "$num";
}

#detect the postfix of the image, png or jpg
sub get_img_postfix{
    my ($b)=@_;         #input is the parent URL of a image;
    $b="$b/001.jpg";
    my $a=new LWP::UserAgent;
    my $r=$a->get($b);
    return "jpg" unless $r->filename ne "001.jpg";
    return "png";
}

#print progress bar
sub print_progress{
    my $len=32;      #Total width of the console progress bar;
    my $c=shift;
    my $l=$end_series-$start_series;
    ($l==0) || ($l=1);
    if($l<=$len){
        my $t=$len/$l;
        foreach(0..$t){
            print "#";
        }
        $progress_len+=$t;
    }else{
        my $t=$l/$len;
        if($c/$t==0){
            print "#";
        }
    }
}
